package cn.shujuhai.qtadmin.platform.pluging.security;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import com.fasterxml.jackson.databind.ObjectMapper;

import cn.shujuhai.qtadmin.platform.kit.CommonKit;
import cn.shujuhai.qtadmin.platform.pluging.result.Result;

/**
 * 登陆成功返回处理器
 *
 * @author dch798
 * @date 2021/08/26 22:02
 **/
@Component
public class MyAuthenticationSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
        Authentication authentication) throws ServletException, IOException {
        if (CommonKit.isJson(request)) {
            response.setContentType("application/json; charset=UTF-8");
            PrintWriter writer = response.getWriter();
            writer.write(new ObjectMapper().writeValueAsString(Result.success("登陆成功", authentication.getPrincipal())));
            writer.flush();
            writer.close();
        } else {
            super.onAuthenticationSuccess(request, response, authentication);
        }
    }
}
